package com.question.aspect;


import com.question.Constant.BaseConstant;
import com.question.Exception.BaseException;
import com.question.Vo.SessionWebUserDto;
import com.question.annotation.GlobalInterceptor;
import com.question.annotation.VerifyParams;
import com.question.utils.StringTools;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.ArrayUtils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import java.lang.reflect.Method;
import java.lang.reflect.Parameter;


@Aspect
@Component("GlobalOperation")
public class GlobalOperation {
    private static final String[] TYPE_NAME = {"java.lang.String", "java.lang.Integer", "java.lang.Long"};

    @Pointcut("@annotation(com.question.annotation.GlobalInterceptor)")
    private void requestInterceptor(){

    }
    @Around("requestInterceptor()")
    public Object InterceptorDo(ProceedingJoinPoint point) throws BaseException {
        try {
            Object target = point.getTarget();
            Object[] arguments = point.getArgs();
            String methodName = point.getSignature().getName();
            // 访问目标方法的参数名称parameterNames和方法method
            Class<?>[] paramter = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
            Method method = target.getClass().getMethod(methodName, paramter);
            //获取目标方法注解的类
            GlobalInterceptor interceptor = method.getAnnotation(GlobalInterceptor.class);
            if (null == interceptor) {
                return null;
            }
            //判断是否需要登录
            if (interceptor.checkLogin() || interceptor.checkAdmin()) {
                checklogin(interceptor.checkAdmin());
            }
            //是否需要校验参数
            if (interceptor.checkParam()) {
                System.out.println("12333");
                validateParams(method, arguments);
            }
            //调用原始方法执行
            Object pointResult = point.proceed();
            return pointResult;

        } catch (Exception e) {
            System.out.println(e);
            throw new BaseException(e.getMessage());

        } catch (Throwable throwable) {
            System.out.println(throwable);
            throw new BaseException("参数错误4");
//            throwable.printStackTrace();
        }
//        return null;


    }
    private void checklogin(Boolean checkAdmin){
        HttpServletRequest httpServletRequest= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession httpSession=httpServletRequest.getSession();
        SessionWebUserDto obj= (SessionWebUserDto) httpSession.getAttribute(BaseConstant.key);
        if(null == obj){
            throw new BaseException("登录超时，请重新登录");
        }
//        if(checkAdmin && !obj.getAdmin()){
//            throw new BaseException("404");
//        }
    }
    //获取方法中的参数
    private void validateParams(Method method, Object[] arguments) {
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            Object value = arguments[i];
            VerifyParams verifyParams = parameter.getAnnotation(VerifyParams.class);

            if (verifyParams == null) {
                continue;
            }
            if (ArrayUtils.contains(TYPE_NAME, parameter.getParameterizedType().getTypeName())) {
                checkValue(value, verifyParams);
            } else {

            }
        }
    }

    private void checkObjValue(Parameter parameter, Object value) {

    }

    private void checkValue(Object value, VerifyParams verifyParams) {
        Boolean isEmpty = value == null || StringTools.isEmpty(value.toString());
        System.out.println(isEmpty + "isempty" + value);
        Integer length = value == null ? 0 : value.toString().length();
        System.out.println(isEmpty + "isempty");
        if (isEmpty && verifyParams.required()) {
            throw new BaseException("参数错误1");
        }
        if (!isEmpty && verifyParams.max() != -1 && verifyParams.max() < length || verifyParams.min() != -1 && verifyParams.min() > length) {
            throw new BaseException("参数错误2");

        }

    }
}
